package collision;

import java.util.LinkedList;

import math.Vector2D;
import entity.Entity;
import entity.units.AirUnit;
import entity.units.GroundUnit;

//test and fix collisions
public class Collision
{
	public static void fixAllDynamicEntityCollisions( LinkedList<Entity> list )
	{
		for( Entity e : list )
		{
			if( e instanceof AirUnit && ((AirUnit)e).isEnabled() )
				fixCollisions( (AirUnit)e, list );
			if( e instanceof GroundUnit && ((GroundUnit)e).isEnabled() )
				fixCollisions( (GroundUnit)e, list );
		}
	}
	
	private static void fixCollisions( AirUnit current, LinkedList<Entity> list )
	{
		for( Entity e : list )
		{
			if( current.equals( e ) || !( e instanceof AirUnit ) )
				continue;
			
			if( !((AirUnit)e).isEnabled() )
				continue;
			
			Vector2D toEntity = Vector2D.subtract( e.getPosition(), current.getPosition() );
			
			double distance = toEntity.getMagnitude();
			
			double amountOfOverlap = current.getRadius() + e.getRadius() - distance;
			
			if( amountOfOverlap >= 0 )
			{
				toEntity.setMagnitude( amountOfOverlap / 2 );
				e.getPosition().add( toEntity );
				current.getPosition().subtract( toEntity );
			}
		}
	}
	
	private static void fixCollisions( GroundUnit current, LinkedList<Entity> list )
	{
		for( Entity e : list )
		{
			if( current.equals( e ) || !( e instanceof GroundUnit ) )
				continue;
			
			if( !((GroundUnit)e).isEnabled() )
				continue;
			
			Vector2D toEntity = Vector2D.subtract( e.getPosition(), current.getPosition() );
			
			double distance = toEntity.getMagnitude();
			
			double amountOfOverlap = current.getRadius() + e.getRadius() - distance;
			
			if( amountOfOverlap >= 0 )
			{
				toEntity.setMagnitude( amountOfOverlap / 2 );
				e.getPosition().add( toEntity );
				current.getPosition().subtract( toEntity );
			}
		}
	}
}
